<template>
  <div class="feedback">
    <div class="searchDiv">
      <Form :model="searchItem" :label-width="80">
        <Row :gutter="10">
          <Col span="6">
            <FormItem label="事件主题">
              <Input v-model="searchItem.subject" placeholder="请输入"></Input>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="涉及设备">
              <Input v-model="searchItem.aboutEquip" placeholder="请输入"></Input>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="事件来源">
              <Input v-model="searchItem.eventSource" placeholder="请输入"></Input>
            </FormItem>
          </Col>
           <Col span="6">
            <FormItem label="事件后果">
              <Input v-model="searchItem.eventConsequence" placeholder="请输入"></Input>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="发生时间">
              <DatePicker
                type="datetime"
                @on-change="time" format="yyyy-MM-dd HH:mm:ss"
                v-model="searchItem.eventTime"
                placeholder="Select date"
                style="width: 100%"
              ></DatePicker>
            </FormItem>
          </Col>
          <Col span="6">
            <FormItem label="关键字">
              <Input v-model="searchItem.eventKeyword" placeholder="请输入"></Input>
            </FormItem>
          </Col>
           <Col span="6">
            <FormItem label="纠正行动">
              <Input v-model="searchItem.correctAction" placeholder="请输入"></Input>
            </FormItem>
          </Col>
          <Col span="6">
            <Button type="primary" class="marRight" @click="searchItem.pageNo=1;getDataList()">查询</Button>
            <Button type="success" class="marRight" @click="add">新增经验反馈</Button>
            <Button type="primary" @click="downBtn">导出Excel</Button>
          </Col>
        </Row>
      </Form>
    </div>
    <Table border :total="total" :loading="loading" :columns="columns" :data="tableData"></Table>
     <Page show-total :total="total" :current="searchItem.pageNo" :page-size="searchItem.pageSize" @on-change="changePage"  style="margin:20px auto;text-align:center"/>
    <!-- 新增弹窗开始 -->
    <Modal :mask-closable="false" v-model="modal1" :title="title1" width="800" >
           <Form :model="formItem" :label-width="120">
             <div class="baseTitle">外部事件分析</div>
             <Row :gutter="10" class="xzjz">
                   <Col span="12">
                    <FormItem label="事件主题：">
                      <Input v-model="formItem.subject" :maxlength="20" placeholder="请输入"></Input>
                    </FormItem>
                  </Col>
                  <Col span="12">
                    <FormItem label="涉及设备：">
                      <Input v-model="formItem.aboutEquip" :maxlength="20" placeholder="请输入"></Input>
                    </FormItem>
                  </Col>
                  <Col span="12">
                    <FormItem label="事件来源：">
                      <Input v-model="formItem.eventSource" :maxlength="20" placeholder="请输入"></Input>
                    </FormItem>
                  </Col>
                  <Col span="12">
                    <FormItem label="事发时间：">
                      <DatePicker
                      type="datetime"
                      @on-change="time1" format="yyyy-MM-dd HH:mm:ss"
                      v-model="formItem.eventTime"
                      placeholder="Select date"
                      style="width: 100%"
                    ></DatePicker>
                    </FormItem>
                  </Col>
                  <Col span="12">
                    <FormItem label="关键字：">
                      <Input v-model="formItem.eventKeyword" :maxlength="20" placeholder="请输入"></Input>
                    </FormItem>
                  </Col>
                   <Col span="12">
                    <FormItem label="事件后果：">
                      <Input v-model="formItem.eventConsequence" :maxlength="20" placeholder="请输入"></Input>
                    </FormItem>
                  </Col>
                  <Col span="12">
                    <FormItem label="事件描述：">
                      <Input type="textarea" v-model="formItem.eventDesc" :maxlength="200" placeholder="请输入"></Input>
                    </FormItem>
                  </Col>
                  <Col span="12">
                    <FormItem label="原因分析：">
                      <Input type="textarea" v-model="formItem.reasonAnalysis" :maxlength="200" placeholder="请输入"></Input>
                    </FormItem>
                  </Col>
                  <Col span="24">
                    <FormItem label="纠正行动：">
                      <Input type="textarea" v-model="formItem.correctAction" :maxlength="200" placeholder="请输入"></Input>
                    </FormItem>
                  </Col>
             <div class="baseTitle">内部反馈</div>
                 <Col span="12">
                   <FormItem label="是否需要修改公司程序或流程：">
                      <Input type="textarea" v-model="formItem.innerFeedback" :maxlength="50" placeholder="请输入"></Input>
                    </FormItem>
                 </Col>
                 <Col span="12">
                   <FormItem label="其他反馈行动：">
                      <Input type="textarea" v-model="formItem.outerFeedback" :maxlength="200" placeholder="请输入"></Input>
                    </FormItem>
                 </Col>

                <div class="baseTitle">后续行动</div>
                 <Col span="12">
                   <FormItem label="改进行动：">
                     <Input v-model="hyform.action" :maxlength="50" placeholder="请输入"></Input>
                    </FormItem>
                 </Col>
                 <Col span="12">
                   <FormItem label="负责人：">
                     <Input v-model="hyform.principal" :maxlength="20" placeholder="请输入"></Input>
                    </FormItem>
                 </Col>
                 <Col span="12">
                   <FormItem label="完成期限：">
                     <DatePicker
                      type="datetime"
                      @on-change="time2" format="yyyy-MM-dd HH:mm:ss"
                      v-model="hyform.completeDeadline"
                      placeholder="Select date"
                      style="width:100%;"
                    ></DatePicker>
                    </FormItem>
                 </Col>
                 <Col span="12">
                   <FormItem label="完成状态：">
                     <Input v-model="hyform.status" style="width:100px;"  placeholder="请输入"></Input>
                    </FormItem>
                 </Col>
                <Col span="24">
                   <FormItem label="上传附件：">
                     <Upload
                        style="float:left;margin-right:10px;"
                          :show-upload-list='false'
                          :headers='fileheader'
                          :on-success='fileSuccess'
                          :action="apihost+'/admin-api/admins/upload/uploadFile'">
                          <Button icon="ios-cloud-upload-outline">选择附件</Button>
                      </Upload>
                      <Button type="default" @click="addYc"> 添加</Button>
                      <div v-if="hyform.url!=''" style="margin-right:10px;">
                          <span style="">{{hyform.url.substring(hyform.url.lastIndexOf('/')+1)}}</span>
                          <Button size="small" style="margin-left:30px;margin-right:10px;"  @click="xiazai(hyform.url)" type="primary">下载文件</Button>
                          <Button size="small"  @click="hyform.url=''" type="error">删除</Button>
                      </div>


                   </FormItem>
                 </Col>
                <Col span="24" style="margin-bottom:10px;">
                    <Table border :columns="columns2" :data="tableData2"></Table>
                  </Col>
                 <div class="baseTitle">填报信息</div>
                 <Col span="12">
                   <FormItem label="记录人：">
                     <Input v-model="recordName" disabled placeholder="请输入"></Input>
                   </FormItem>
                 </Col>
                 <Col span="12">
                   <FormItem label="记录时间：">
                     <Input v-model="recordTime" disabled placeholder="请输入"></Input>
                    </FormItem>
                 </Col>
             </Row>
           </Form>
           <div slot="footer">
            <Button type="primary" :loading="btnClick" @click="ok">确定</Button>
            <Button @click="addWtgz">添加至问题跟踪</Button>
            <Button @click="modal1=false">取消</Button>
           </div>
    </Modal>
    <Modal :mask-closable="false" v-model="modal2" width="360" class-name="vertical-center-modal" @on-ok="remove(delID)">
        <p slot="header" style="color:#f60;text-align:center">
            <Icon type="ios-information-circle"></Icon>
            <span>确认删除</span>
        </p>
        <div style="text-align:center">
            <p>确认删除此数据么？</p>
        </div>
    </Modal>
    <!-- 新增弹窗结束 -->
  </div>
</template>

<script>
import { getToken } from '@/libs/util'
import {
  getSelectOption,
  getAllPeople,getTime
} from '@/api/select'
import {
  getTableData,
  add,
  update,
  del,
  getHX,
  delHX,
  addIssure,downExcel
} from '@/api/feedback'

export default {
  data () {
    return {
      btnClick:false,
      recordName: localStorage.getItem('recordUserName'),
      recordId:localStorage.getItem('recordUserId'),
      recordTime:getTime(),
      fileheader: {
        Authorization: 'Bearer ' + (getToken() ? getToken() : '')
      },
      loading:true,
      peopleList:[],
      powerStationList:[],
      HBnumberList:[],
      JZnumberList:[],
      reasonSortList:[],
      houguoList:[],
      delID: 0,
      modal2: false,
      total: 0,
      modal1: false,
      title1: '新增经验反馈',
      isAdd: true,
      hyform:{
        url:'',
        name:''
      },
      searchItem: {
         pageNo: 1,
        pageSize: 10,
      },
      formItem: {},
      columns: [
        {
          type: 'index',
          width: 60,
          title: '序号',
          align: 'center'
        },
        {
          title: '事件主题',
          key: 'subject'
        },
        {
          title: '涉及设备',
          key: 'aboutEquip'
        },
        {
          title: '事件来源',
          key: 'eventSource'
        },
        {
          title: '关键字',
          key: 'eventKeyword'
        },
        {
          title: '发生时间',
          key: 'eventTime'
        },
        {
          title: '事件后果',
          key: 'eventConsequence'
        },
        {
          title: '纠正行动',
          key: 'correctAction'
        },
        {
          title: '操作',
          key: 'action',
          width: 200,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.edit(JSON.stringify(params));
                    }
                  }
                },
                '编辑'
              ),
              h(
                'Button',
                {
                  props: {
                    type: 'error',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      this.openDel(params.row.id)
                    }
                  }
                },
                '删除'
              )
            ])
          }
        }
      ],
      tableData: [],
      columns2:[
          {
          title: "改进行动",
          key: "action"
        },
        {
          title: "负责人",
          key: "principal"
        },
        {
          title: "完成期限",
          key: "completeDeadline"
        },
        {
          title: "完成状态",
          key: "status",
        },
        {
          title: "记录人",
          key: "recordName",
        },
        {
          title: "操作",
          key: "action",
          width:160,
          align: "center",
          render: (h, params) => {
            if(params.row.url==''||params.row.url==undefined){
               return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small"
                  },
                  on: {
                    click: () => {
                      this.remove2(params.index,params.row.id);
                    }
                  }
                },
                "删除"
              )
            ]);
            }else{
               return h("div", [
              h(
                "Button",
                {
                  props: {
                    size: "small"
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      window.open(params.row.url,'_blank')
                    }
                  }
                },
                "下载附件"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small"
                  },
                  on: {
                    click: () => {
                      this.remove2(params.index,params.row.id);
                    }
                  }
                },
                "删除"
              )
            ]);
            }

          }
        }
      ],
      tableData2: []
    }
  },
  methods: {
    downBtn(){
      downExcel(this.searchItem).then(res => {
         const blob = new Blob([res], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;'});

        const ie = navigator.userAgent.match(/MSIE\s([\d.]+)/),
            ie11 = navigator.userAgent.match(/Trident\/7.0/) && navigator.userAgent.match(/rv:11/),
            ieEDGE = navigator.userAgent.match(/Edge/g),
            ieVer = (ie ? ie[1] : (ie11 ? 11 : (ieEDGE ? 12 : -1)));
        console.log('ie:' + ie);
        console.log('ieVer:' + ieVer);
        if (ie && ieVer < 10) {
            this.message.error('No blobs on IE<10');
            return;
        }
        if (ieVer > -1) {
            window.navigator.msSaveBlob(blob, '经验反馈.xlsx');
        } else {
            const url = window.URL.createObjectURL(blob);
            let link = document.createElement('a');
            link.setAttribute('href', url);
            link.setAttribute('download', '经验反馈.xlsx');
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
        // const blob = new Blob([res]);//处理文档流
        //   const fileName = '经验反馈.xlsx';
        //   const elink = document.createElement('a');
        //   elink.download = fileName;
        //   elink.style.display = 'none';
        //   elink.href = URL.createObjectURL(blob);
        //   document.body.appendChild(elink);
        //   elink.click();
        //   URL.revokeObjectURL(elink.href); // 释放URL 对象
        //   document.body.removeChild(elink);
      })
    },
     xiazai(url){
       window.open(url)
    },
    fileSuccess (response, file, fileList) {
      this.hyform.name=file.name
      this.hyform.url = response.data
    },
     addYc(){
      if(this.hyform.action==''||this.hyform.action==undefined){
        this.$Message.info('请填写改进行动！');
        return false;
      }
      if(this.hyform.principal==''||this.hyform.principal==undefined){
        this.$Message.info('请填写负责人！');
        return false;
      }
      if(this.hyform.completeDeadline==''){
        this.$Message.info('请选择完成期限！');
        return false;
      }
      if(this.hyform.status==''||this.hyform.status==undefined){
        this.$Message.info('请填写完成状态！');
        return false;
      }

      this.hyform.recordId=this.recordId;
      this.hyform.recordName=this.recordName;
      this.tableData2.push(this.hyform);
      this.hyform={ url:'',name:''};
    },
    remove2(index,id) {
      this.tableData2.splice(index, 1);
      delHX({ id: id }).then(res => {
        if (res.code == 0) {
          this.$Message.info('删除成功')
        } else {
          this.$Message.info(res.message)
        }
      })
    },
    //获取所有人员
    getAllPeople(){
      getAllPeople(
        null
      ).then(res => {
        this.peopleList = res.data
      }).catch(err => {
        console.error('err>' + JSON.stringify(err))
      })
    },
    // 获取后果分类
    // houguo () {
    //   getSelectOption(
    //     {
    //       code: 'consequence_key'
    //     }
    //   ).then(res => {
    //     this.houguoList = res.data
    //   }).catch(err => {
    //     console.error('err>' + JSON.stringify(err))
    //   })
    // },
    // // 获取原因分类
    // reasonSort () {
    //   getSelectOption(
    //     {
    //       code: 'reason_catory_key'
    //     }
    //   ).then(res => {
    //     this.reasonSortList = res.data
    //   }).catch(err => {
    //     console.error('err>' + JSON.stringify(err))
    //   })
    // },
    // 获取电站类型列表
    // powerStation () {
    //   getSelectOption(
    //     {
    //       code: 'dianzhan'
    //     }
    //   ).then(res => {
    //     this.powerStationList = res.data
    //   }).catch(err => {
    //     console.error('err>' + JSON.stringify(err))
    //   })
    // },
    // HBnumber () {
    //   getSelectOption(
    //     {
    //       code: 'hd_code'
    //     }
    //   ).then(res => {
    //     this.HBnumberList = res.data
    //   }).catch(err => {
    //     console.error('err>' + JSON.stringify(err))
    //   })
    // },
    // JZnumber () {
    //   getSelectOption(
    //     {
    //       code: 'jizu_code'
    //     }
    //   ).then(res => {
    //     this.JZnumberList = res.data
    //   }).catch(err => {
    //     console.error('err>' + JSON.stringify(err))
    //   })
    // },
    openDel (id) {
      this.modal2 = true
      this.delID = id
      // this.remove(params.index);
    },
    time (e) {
      this.searchItem.eventTime = e
    },
    time1 (e) {
      this.formItem.eventTime = e
    },
    time2 (e) {
      console.log('e>' + e)
      this.hyform.completeDeadline = e
    },
    remove (id) {
      del({ id: id }).then(res => {
        if (res.code == 0) {
          this.$Message.info('删除成功')
          this.searchItem.pageNo=1
          this.getDataList()
        } else {
          this.$Message.info(res.message)
        }
      }).catch(err => {
        console.error('err>' + JSON.stringify(err))
      })
    },
    add () {
      this.isAdd = true
      this.title1 = '新增经验反馈';
      this.formItem={};
      this.tableData2=[];
      this.modal1 = true;
    },
    edit (params) {
      this.isAdd = false
      this.title1 = '编辑经验反馈'
      this.formItem = JSON.parse(params).row
      this.modal1 = true;
      getHX({knowledgeId:JSON.parse(params).row.id}).then(res => {
        if (res.code == 0) {
          this.tableData2 = res.data
        }
      })
    },
    ok () {
      this.btnClick=true;
      let params = this.formItem;
      params.recordName=this.recordName;
      params.recordId=this.recordId;
      params.recordTime=this.recordTime;
      for(var i=0;i<this.tableData2.length;i++){
        params["list["+i+"].action"]=this.tableData2[i].action;
        params["list["+i+"].completeDeadline"]=this.tableData2[i].completeDeadline;
        params["list["+i+"].principal"]=this.tableData2[i].principal;
        params["list["+i+"].recordId"]=this.tableData2[i].recordId;
        params["list["+i+"].recordName"]=this.tableData2[i].recordName;
        params["list["+i+"].status"]=this.tableData2[i].status;
        params["list["+i+"].url"]=this.tableData2[i].url;
      }
      if (this.isAdd) {
        add(params).then(res => {
          console.log('res>' + JSON.stringify(res))
          if (res.code == 0) {
            this.$Message.info('新增成功')
            this.getDataList()
            this.modal1=false;
            this.btnClick=false;
          } else {
            this.$Message.info(res.message)
            this.btnClick=false;
          }
        }).catch(err => {
          console.error('err>' + JSON.stringify(err))
        })
      } else {
        params.eventTime=this.timeFormat(params.eventTime);
        update(params).then(res => {
          console.log('res>' + JSON.stringify(res))
          if (res.code == 0) {
            this.$Message.info('修改成功')
            this.getDataList()
            this.modal1=false;
            this.btnClick=false;
          } else {
            this.$Message.info(res.message)
            this.btnClick=false;
          }
        }).catch(err => {
          console.error('err>' + JSON.stringify(err))
        })
      }
    },
    addWtgz () {
      // let params = this.formItem
      // params.recordName=this.recordName;
      // params.recordId=this.recordId;
      // params.recordTime=this.recordTime;
      // for(var i=0;i<this.tableData2.length;i++){
      //   params["list["+i+"].action"]=this.tableData2[i].action;
      //   params["list["+i+"].completeDeadline"]=this.tableData2[i].completeDeadline;
      //   params["list["+i+"].principal"]=this.tableData2[i].principal;
      //   params["list["+i+"].recordId"]=this.tableData2[i].recordId;
      //   params["list["+i+"].recordName"]=this.tableData2[i].recordName;
      //   params["list["+i+"].status"]=this.tableData2[i].status;
      //   params["list["+i+"].url"]=this.tableData2[i].url;
      // }
      // if (this.isAdd) {
      //   addIssure(params).then(res => {
      //     console.log('res>' + JSON.stringify(res))
      //     if (res.code == 0) {
      //       this.$Message.info('添加成功')
      //       this.getDataList()
      //     } else {
      //       this.$Message.info(res.message)
      //     }
      //   }).catch(err => {
      //     console.error('err>' + JSON.stringify(err))
      //   })
      // } else {
      //   addIssure(params).then(res => {
      //     console.log('res>' + JSON.stringify(res))
      //     if (res.code == 0) {
      //       this.$Message.info('新增成功')
      //       this.getDataList()
      //     } else {
      //       this.$Message.info(res.message)
      //     }
      //   }).catch(err => {
      //     console.error('err>' + JSON.stringify(err))
      //   })
      // }
      // this.modal1=false;
      this.$router.push(
        {
          path:'/problem/tefectTracking',
          query:{
            open:true,
            issue:this.formItem.subject,
            source:"经验反馈",
            description:this.formItem.eventDesc,
            reasonAnalyze:this.formItem.reasonAnalysis
          }
        }
      )
    },
    timeFormat (time) {
      if(time instanceof Date==false){
        return time
      }
                const dateTime = new Date(time)
                const year = dateTime.getFullYear()
                const month = this.addZero(dateTime.getMonth() + 1)
                const date = this.addZero(dateTime.getDate())
                const hour = this.addZero(dateTime.getHours())
                const minute = this.addZero(dateTime.getMinutes())
                const second = this.addZero(dateTime.getSeconds())
                return year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second
            },
            addZero (v) {
                return v < 10 ? '0' + v : v
            },
    /** 分页 */
    changePage (pageNo) {
      this.searchItem.pageNo = pageNo
      this.getDataList()
    },
    getDataList () {
      getTableData(this.searchItem).then(res => {
        console.log('res>' + JSON.stringify(res))
        if (res.code == 0) {
          this.total = res.data.total
          let list = res.data.list
          this.tableData = res.data.list
          this.loading=false
        }
      }).catch(err => {
        console.error('err>' + JSON.stringify(err))
      })
    }
  },
  mounted () {},
  created () {
    // this.powerStation();
    // this.HBnumber();
    // this.JZnumber();
    // this.reasonSort();
    // this.houguo();
    this.getAllPeople();
    this.getDataList()
  }
}
</script>

<style lang="less">
.feedback {
  background: #fff;
  height: 100%;
  padding: 15px;
  font-size: 14px;
  .searchDiv {
    .marRight {
      margin-right: 15px;
    }
  }
  .ivu-form-item {
    margin-bottom: 15px;
  }
}
.baseTitle {
    font-weight: bold;
    font-size:16px;
    margin-bottom:10px;
  }
 .xzjz  {
   .ivu-form-item {
    margin-bottom: 10px;
  }
 }
 .baseTitle {
    font-weight: bold;
    font-size:16px;
    margin-bottom:10px;
  }
  // .ivu-upload-select {
  //   float:left;
  // }
  // .ivu-upload-list {
  //   float:left;
  //   margin-left:10px;
  //   margin-top:0px;
  // }
  // .ivu-upload-list-file {
  //   padding:0px;
  // }
</style>
